using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using EIMS.Data;
using EIMS.Models;
using EIMS.Models.Enums;
using EIMS.Models.ViewModels;
using System.Security.Claims;
using System.ComponentModel.DataAnnotations;

namespace EIMS.Controllers
{
    [Authorize]
    public class CustomerController : Controller
    {
        private readonly ApplicationDbContext _context;

        public CustomerController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Customer
        public async Task<IActionResult> Index(string searchString, CustomerType? type, CustomerStatus? status)
        {
            var customersQuery = _context.Customers.AsQueryable();

            // 搜索过滤
            if (!string.IsNullOrEmpty(searchString))
            {
                customersQuery = customersQuery.Where(c => 
                    c.Name.Contains(searchString) || 
                    c.CustomerNumber.Contains(searchString) ||
                    c.ContactPerson.Contains(searchString) ||
                    c.PhoneNumber.Contains(searchString) ||
                    c.Email.Contains(searchString)
                );
            }

            // 类型过滤
            if (type.HasValue)
            {
                customersQuery = customersQuery.Where(c => c.Type == type);
            }

            // 状态过滤
            if (status.HasValue)
            {
                customersQuery = customersQuery.Where(c => c.Status == status);
            }

            // 将枚举转换为下拉列表选项
            ViewBag.TypeList = Enum.GetValues(typeof(CustomerType))
                .Cast<CustomerType>()
                .Select(t => new SelectListItem
                {
                    Value = ((int)t).ToString(),
                    Text = GetEnumDisplayName(t),
                    Selected = type.HasValue && type.Value == t
                })
                .ToList();

            ViewBag.StatusList = Enum.GetValues(typeof(CustomerStatus))
                .Cast<CustomerStatus>()
                .Select(s => new SelectListItem
                {
                    Value = ((int)s).ToString(),
                    Text = GetEnumDisplayName(s),
                    Selected = status.HasValue && status.Value == s
                })
                .ToList();

            // 把搜索条件放入ViewBag用于视图中保留搜索条件
            ViewBag.SearchString = searchString;
            ViewBag.Type = type;
            ViewBag.Status = status;

            return View(await customersQuery.ToListAsync());
        }

        // GET: Customer/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customers
                .FirstOrDefaultAsync(c => c.Id == id);

            if (customer == null)
            {
                return NotFound();
            }

            // 创建客户详情视图模型
            var viewModel = new CustomerDetailViewModel
            {
                Customer = customer,
                Contacts = await _context.CustomerContacts
                    .Where(c => c.CustomerId == id)
                    .ToListAsync(),
                Transactions = await _context.CustomerTransactions
                    .Where(t => t.CustomerId == id)
                    .ToListAsync()
            };

            // 计算统计数据
            viewModel.TransactionCount = viewModel.Transactions.Count;
            viewModel.TotalTransactionAmount = viewModel.Transactions.Sum(t => t.Amount);
            viewModel.UnpaidAmount = viewModel.Transactions
                .Where(t => t.PaymentStatus != Models.Enums.PaymentStatus.Paid)
                .Sum(t => t.Amount);

            return View(viewModel);
        }

        // GET: Customer/Create
        [Authorize(Roles = "Administrator,Manager")]
        public IActionResult Create()
        {
            PrepareViewBags();
            return View();
        }

        // POST: Customer/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Create([Bind("Id,CustomerNumber,Name,Type,CreditRating,ContactPerson,PhoneNumber,Email,Address,Fax,Website,Remarks,Status")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                // 检查客户编号是否已存在
                bool exists = await _context.Customers.AnyAsync(c => c.CustomerNumber == customer.CustomerNumber);
                if (exists)
                {
                    ModelState.AddModelError("CustomerNumber", "该客户编号已存在");
                    PrepareViewBags();
                    return View(customer);
                }

                // 设置创建时间
                customer.CreatedAt = DateTime.Now;
                
                _context.Add(customer);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "客户添加成功！";
                return RedirectToAction(nameof(Index));
            }
            
            PrepareViewBags();
            return View(customer);
        }

        // GET: Customer/Edit/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }
            
            PrepareViewBags();
            return View(customer);
        }

        // POST: Customer/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int id, [Bind("Id,CustomerNumber,Name,Type,CreditRating,ContactPerson,PhoneNumber,Email,Address,Fax,Website,Remarks,Status,CreatedAt")] Customer customer)
        {
            if (id != customer.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                // 检查客户编号是否已存在于其他记录中
                bool exists = await _context.Customers
                    .AnyAsync(c => c.CustomerNumber == customer.CustomerNumber && c.Id != customer.Id);
                if (exists)
                {
                    ModelState.AddModelError("CustomerNumber", "该客户编号已被其他客户使用");
                    PrepareViewBags();
                    return View(customer);
                }

                try
                {
                    // 设置更新时间
                    customer.UpdatedAt = DateTime.Now;
                    
                    _context.Update(customer);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "客户更新成功！";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerExists(customer.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            
            PrepareViewBags();
            return View(customer);
        }

        // GET: Customer/Delete/5
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customers
                .FirstOrDefaultAsync(c => c.Id == id);
                
            if (customer == null)
            {
                return NotFound();
            }

            return View(customer);
        }

        // POST: Customer/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            
            // TODO: 检查是否有关联订单等信息
            // 目前先简单删除
            
            _context.Customers.Remove(customer);
            await _context.SaveChangesAsync();
            
            TempData["SuccessMessage"] = "客户删除成功！";
            return RedirectToAction(nameof(Index));
        }

        private bool CustomerExists(int id)
        {
            return _context.Customers.Any(e => e.Id == id);
        }
        
        private void PrepareViewBags()
        {
            ViewBag.Types = new SelectList(Enum.GetValues(typeof(CustomerType))
                .Cast<CustomerType>()
                .Select(t => new { Id = (int)t, Name = GetEnumDisplayName(t) }),
                "Id", "Name");
                
            ViewBag.CreditRatings = new SelectList(Enum.GetValues(typeof(CreditRating))
                .Cast<CreditRating>()
                .Select(r => new { Id = (int)r, Name = GetEnumDisplayName(r) }),
                "Id", "Name");
                
            ViewBag.Statuses = new SelectList(Enum.GetValues(typeof(CustomerStatus))
                .Cast<CustomerStatus>()
                .Select(s => new { Id = (int)s, Name = GetEnumDisplayName(s) }),
                "Id", "Name");
        }

        // 获取枚举的Display属性值
        private string GetEnumDisplayName<T>(T enumValue) where T : Enum
        {
            var displayAttribute = enumValue.GetType()
                .GetField(enumValue.ToString())
                .GetCustomAttributes(typeof(DisplayAttribute), false)
                .FirstOrDefault() as DisplayAttribute;

            return displayAttribute?.Name ?? enumValue.ToString();
        }

        #region 客户联系人管理

        // GET: Customer/AddContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }

            var viewModel = new CustomerContactViewModel
            {
                CustomerId = customer.Id,
                CustomerName = customer.Name
            };

            return View(viewModel);
        }

        // POST: Customer/AddContact
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddContact(CustomerContactViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var contact = new CustomerContact
                {
                    Name = viewModel.Name,
                    Position = viewModel.Position,
                    Department = viewModel.Department,
                    Mobile = viewModel.Mobile,
                    Phone = viewModel.Phone,
                    Email = viewModel.Email,
                    SocialMedia = viewModel.SocialMedia,
                    IsPrimary = viewModel.IsPrimary,
                    Remarks = viewModel.Remarks,
                    CustomerId = viewModel.CustomerId,
                    CreatedAt = DateTime.Now
                };

                // 如果设置为主要联系人，将其他联系人设为非主要
                if (viewModel.IsPrimary)
                {
                    var primaryContacts = await _context.CustomerContacts
                        .Where(c => c.CustomerId == viewModel.CustomerId && c.IsPrimary)
                        .ToListAsync();
                        
                    foreach (var primaryContact in primaryContacts)
                    {
                        primaryContact.IsPrimary = false;
                        _context.Update(primaryContact);
                    }
                }

                _context.Add(contact);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "联系人添加成功！";
                return RedirectToAction(nameof(Details), new { id = viewModel.CustomerId });
            }

            // 如果验证失败，重新获取客户名称
            var customer = await _context.Customers.FindAsync(viewModel.CustomerId);
            if (customer != null)
            {
                viewModel.CustomerName = customer.Name;
            }
            
            return View(viewModel);
        }

        // GET: Customer/EditContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.CustomerContacts
                .Include(c => c.Customer)
                .FirstOrDefaultAsync(c => c.Id == id);
                
            if (contact == null)
            {
                return NotFound();
            }

            var viewModel = new CustomerContactViewModel
            {
                Id = contact.Id,
                Name = contact.Name,
                Position = contact.Position,
                Department = contact.Department,
                Mobile = contact.Mobile,
                Phone = contact.Phone,
                Email = contact.Email,
                SocialMedia = contact.SocialMedia,
                IsPrimary = contact.IsPrimary,
                Remarks = contact.Remarks,
                CustomerId = contact.CustomerId,
                CustomerName = contact.Customer.Name
            };

            return View(viewModel);
        }

        // POST: Customer/EditContact/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditContact(int id, CustomerContactViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var contact = await _context.CustomerContacts.FindAsync(id);
                    if (contact == null)
                    {
                        return NotFound();
                    }
                    
                    contact.Name = viewModel.Name;
                    contact.Position = viewModel.Position;
                    contact.Department = viewModel.Department;
                    contact.Mobile = viewModel.Mobile;
                    contact.Phone = viewModel.Phone;
                    contact.Email = viewModel.Email;
                    contact.SocialMedia = viewModel.SocialMedia;
                    contact.Remarks = viewModel.Remarks;
                    contact.UpdatedAt = DateTime.Now;
                    
                    // 如果更改了主要联系人状态
                    if (viewModel.IsPrimary != contact.IsPrimary)
                    {
                        contact.IsPrimary = viewModel.IsPrimary;
                        
                        // 如果设置为主要联系人，将其他联系人设为非主要
                        if (viewModel.IsPrimary)
                        {
                            var primaryContacts = await _context.CustomerContacts
                                .Where(c => c.CustomerId == contact.CustomerId && c.IsPrimary && c.Id != contact.Id)
                                .ToListAsync();
                                
                            foreach (var primaryContact in primaryContacts)
                            {
                                primaryContact.IsPrimary = false;
                                _context.Update(primaryContact);
                            }
                        }
                    }
                    
                    _context.Update(contact);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "联系人更新成功！";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerContactExists(viewModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Details), new { id = viewModel.CustomerId });
            }
            
            return View(viewModel);
        }

        // GET: Customer/DeleteContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.CustomerContacts
                .Include(c => c.Customer)
                .FirstOrDefaultAsync(c => c.Id == id);
                
            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }

        // POST: Customer/DeleteContact/5
        [HttpPost, ActionName("DeleteContact")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteContactConfirmed(int id)
        {
            var contact = await _context.CustomerContacts.FindAsync(id);
            
            if (contact == null)
            {
                return NotFound();
            }
            
            int customerId = contact.CustomerId;
            
            _context.CustomerContacts.Remove(contact);
            await _context.SaveChangesAsync();
            
            TempData["SuccessMessage"] = "联系人删除成功！";
            return RedirectToAction(nameof(Details), new { id = customerId });
        }
        
        private bool CustomerContactExists(int id)
        {
            return _context.CustomerContacts.Any(e => e.Id == id);
        }

        #endregion
        
        #region 客户交易记录管理
        
        // GET: Customer/AddTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }

            var viewModel = new CustomerTransactionViewModel
            {
                CustomerId = customer.Id,
                CustomerName = customer.Name,
                TransactionDate = DateTime.Now,
                TransactionNumber = GenerateTransactionNumber()
            };
            
            PrepareTransactionViewBags();

            return View(viewModel);
        }
        
        // POST: Customer/AddTransaction
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddTransaction(CustomerTransactionViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var transaction = new CustomerTransaction
                {
                    TransactionNumber = viewModel.TransactionNumber,
                    Type = viewModel.Type,
                    TransactionDate = viewModel.TransactionDate,
                    Amount = viewModel.Amount,
                    PaymentStatus = viewModel.PaymentStatus,
                    PaymentDate = viewModel.PaymentDate,
                    OrderId = viewModel.OrderId,
                    Remarks = viewModel.Remarks,
                    CustomerId = viewModel.CustomerId,
                    CreatedAt = DateTime.Now,
                    CreatedBy = User.FindFirstValue(ClaimTypes.Name) ?? User.Identity.Name
                };

                _context.Add(transaction);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "交易记录添加成功！";
                return RedirectToAction(nameof(Details), new { id = viewModel.CustomerId });
            }

            // 如果验证失败，重新获取客户名称
            var customer = await _context.Customers.FindAsync(viewModel.CustomerId);
            if (customer != null)
            {
                viewModel.CustomerName = customer.Name;
            }
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // GET: Customer/EditTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var transaction = await _context.CustomerTransactions
                .Include(t => t.Customer)
                .FirstOrDefaultAsync(t => t.Id == id);
                
            if (transaction == null)
            {
                return NotFound();
            }

            var viewModel = new CustomerTransactionViewModel
            {
                Id = transaction.Id,
                TransactionNumber = transaction.TransactionNumber,
                Type = transaction.Type,
                TransactionDate = transaction.TransactionDate,
                Amount = transaction.Amount,
                PaymentStatus = transaction.PaymentStatus,
                PaymentDate = transaction.PaymentDate,
                OrderId = transaction.OrderId,
                Remarks = transaction.Remarks,
                CustomerId = transaction.CustomerId,
                CustomerName = transaction.Customer.Name
            };

            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // POST: Customer/EditTransaction/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditTransaction(int id, CustomerTransactionViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var transaction = await _context.CustomerTransactions.FindAsync(id);
                    if (transaction == null)
                    {
                        return NotFound();
                    }
                    
                    transaction.TransactionNumber = viewModel.TransactionNumber;
                    transaction.Type = viewModel.Type;
                    transaction.TransactionDate = viewModel.TransactionDate;
                    transaction.Amount = viewModel.Amount;
                    transaction.PaymentStatus = viewModel.PaymentStatus;
                    transaction.PaymentDate = viewModel.PaymentDate;
                    transaction.OrderId = viewModel.OrderId;
                    transaction.Remarks = viewModel.Remarks;
                    
                    _context.Update(transaction);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "交易记录更新成功！";
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerTransactionExists(viewModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Details), new { id = viewModel.CustomerId });
            }
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // GET: Customer/DeleteTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var transaction = await _context.CustomerTransactions
                .Include(t => t.Customer)
                .FirstOrDefaultAsync(t => t.Id == id);
                
            if (transaction == null)
            {
                return NotFound();
            }

            return View(transaction);
        }

        // POST: Customer/DeleteTransaction/5
        [HttpPost, ActionName("DeleteTransaction")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteTransactionConfirmed(int id)
        {
            var transaction = await _context.CustomerTransactions.FindAsync(id);
            
            if (transaction == null)
            {
                return NotFound();
            }
            
            int customerId = transaction.CustomerId;
            
            _context.CustomerTransactions.Remove(transaction);
            await _context.SaveChangesAsync();
            
            TempData["SuccessMessage"] = "交易记录删除成功！";
            return RedirectToAction(nameof(Details), new { id = customerId });
        }
        
        private bool CustomerTransactionExists(int id)
        {
            return _context.CustomerTransactions.Any(t => t.Id == id);
        }
        
        // 准备交易记录的ViewBags
        private void PrepareTransactionViewBags()
        {
            ViewBag.TransactionTypes = new SelectList(Enum.GetValues(typeof(TransactionType))
                .Cast<TransactionType>()
                .Select(t => new { Id = (int)t, Name = GetEnumDisplayName(t) }),
                "Id", "Name");
                
            ViewBag.PaymentStatuses = new SelectList(Enum.GetValues(typeof(PaymentStatus))
                .Cast<PaymentStatus>()
                .Select(p => new { Id = (int)p, Name = GetEnumDisplayName(p) }),
                "Id", "Name");
        }
        
        // 生成交易编号
        private string GenerateTransactionNumber()
        {
            string prefix = "TRX";
            string dateCode = DateTime.Now.ToString("yyyyMMdd");
            string randomCode = new Random().Next(1000, 9999).ToString();
            return $"{prefix}-{dateCode}-{randomCode}";
        }
        
        #endregion
    }
} 